<template>
  <div @mousedown.stop v-if="isShow" class="update-event" :style="{ top: divTop + 'px', left: divLeft + 'px' }">
    <el-card style="max-width: 300px; max-height: 500px" shadow="hover">
      <template #header>
        <p @mousedown.stop>事件详细信息 <span @mousedown.stop @click="close">x</span></p>
      </template>
      <table border="1" cellspacing="0" cellpadding="0">
        <tr>
          <td>事件编号</td>
          <td>
            <el-input
             @mousedown.stop
              size="small"
              v-model="eventNumber"
              placeholder="请输入事件编号"
            />
          </td>
        </tr>
        <tr>
          <td>事件类型</td>
          <td>
            <el-select
            @mousedown.stop
              size="small"
              v-model="eventType"
              placeholder="请选择事件类型"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </td>
        </tr>
        <tr>
          <td>事件等级</td>
          <td>
            <el-select
              size="small"
              v-model="eventLevel"
              placeholder="请选择事件类型"
            >
              <el-option
                v-for="item in options1"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </td>
        </tr>
        <tr>
          <td>发生时间</td>
          <td>
            <el-date-picker
              size="small"
              v-model="eventTime"
              type="datetime"
              placeholder="请输入事件发生时间"
            />
          </td>
        </tr>
        <tr>
          <td>发生地点</td>
          <td>
            <el-input
              size="small"
              v-model="eventAddress"
              placeholder="请输入事件发生地点"
            />
          </td>
        </tr>
        <tr>
          <td>车牌号</td>
          <td>
            <el-input
              size="small"
              t
              v-model="carNumber"
              placeholder="请输入车牌号"
            />
          </td>
        </tr>
        <tr>
          <td>驾驶员</td>
          <td>
            <el-input
              size="small"
              v-model="driverName"
              placeholder="请输入驾驶员姓名"
            />
          </td>
        </tr>
        <tr>
          <td>处理状态</td>
          <td>
            <el-select
              size="small"
              v-model="eventState"
              placeholder="请选择处理状态"
            >
              <el-option
                v-for="item in options2"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </td>
        </tr>
      </table>
      <div class="btns">
        <button @click="submit">提交</button>
        <button @click="close">取消</button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, watch, onUnmounted } from 'vue'
import { storeToRefs } from 'pinia'
import { useMap } from '@/stores/useMap.js'
const isShow = ref(false)
const { map, ggMap } = storeToRefs(useMap())
const isSubmit = ref(false)
const divTop = ref(0)
const divLeft = ref(0)
let currentAttributes = null // 存储当前要素属性
const eventNumber = ref('')
const eventType = ref('')
const eventLevel = ref('')
const eventTime = ref('')
const eventAddress = ref('')
const carNumber = ref('')
const driverName = ref('')
const eventState = ref('')
let position, info, fid, color, top, left

const options = [
  { value: '碰撞', label: '碰撞' },
  { value: '刮擦', label: '刮擦' },
  { value: '翻车', label: '翻车' },
  { value: '碾压', label: '碾压' },
  { value: '失火', label: '失火' },
  { value: '其他', label: '其他' },
]
const options1 = [
  { value: '1', label: '轻微事故' },
  { value: '2', label: '中度事故' },
  { value: '3', label: '重大事故' },
  { value: '4', label: '特大事故' },
]
const options2 = [
  { value: '0', label: '待处理' },
  { value: '1', label: '处理中' },
  { value: '2', label: '已处理' },
]

/*通过坐标,查询地图文档上,对应图层的要素 */
const handleClick = (e) => {
  isShow.value = false
  position = e.coordinate
  updateEvent()
}
//map.value.on('click',handleClick)
const close = () => {
  isShow.value = false
  isSubmit.value = false
}
const submit = () => {
  isSubmit.value = true
  isShow.value = false
}
function querySuccess(result) {
  info = result.SFEleArray[0].AttValue
  eventNumber.value = info[0]
  eventType.value = info[1]
  eventLevel.value = info[2]
  eventTime.value = info[3]
  eventAddress.value = info[4]
  carNumber.value = info[5]
  driverName.value = info[6]
  eventState.value = info[7]
  fid = result.SFEleArray[0].FID
  isShow.value = true
  currentAttributes = [
    eventNumber.value,
    eventType.value,
    eventLevel.value,
    eventTime.value,
    eventAddress.value,
    carNumber.value,
    driverName.value,
    eventState.value,
  ]
}
function queryError(e) {
  console.log('失败')
}
//获取点的属性值
function updateEvent() {
  //创建一个用于查询的点形状
  let pointObj = new Zondy.Object.Point2D(position[0], position[1])
  //设置查询点的搜索半径
  pointObj.nearDis = 0.001
  //1.初始化查询结构对象，设置查询结构包含几何信息
  var queryStruct = new Zondy.Service.QueryFeatureStruct()
  //是否包含几何图形信息
  queryStruct.IncludeGeometry = true
  //是否包含属性信息
  queryStruct.IncludeAttribute = true
  //是否包含图形显示参数
  queryStruct.IncludeWebGraphic = false
  //2.指定查询规则
  var rule = new Zondy.Service.QueryFeatureRule({
    //是否将要素的可见性计算在内
    EnableDisplayCondition: false,
    //是否完全包含
    MustInside: false,
    //是否仅比较要素的外包矩形
    CompareRectOnly: false,
    //是否相交
    Intersect: true,
  })
  //3.实例化查询参数对象
  var queryParam = new Zondy.Service.QueryParameter({
    geometry: pointObj,
    resultFormat: 'json',
    struct: queryStruct,
    rule: rule,
  })
  //4.实例化查询服务对象
  var queryService = new Zondy.Service.QueryDocFeature(
    queryParam,
    'guanggu',
    '2',
    {
      ip: 'localhost',
      port: '8089', //访问IGServer的端口号，.net版为6163，Java版为8089
    }
  )
  //执行查询操作，querySuccess为查询回调函数
  queryService.query(querySuccess, queryError)
}
//更新点的属性值
function updatePoint() {
  let Service = {
    docName: 'guanggu',
    layerId: '2',
  }
  /*1.构建更新点的信息 */
  //创建一个用于查询的点形状
  var gpoint = new Zondy.Object.GPoint(position[0], position[1])
  var fGeom = new Zondy.Object.FeatureGeometry({ PntGeom: [gpoint] })
  //设置添加点要素的图形参数信息
  var pointInfo = new Zondy.Object.CPointInfo({
    Angle: 0,
    Color: color, // 使用动态颜色
    Space: 0,
    SymHeight: 5,
    SymID: 21,
    SymWidth: 5,
  })
  //设置当前点要素的图形参数信息
  var webGraphicInfo = new Zondy.Object.WebGraphicsInfo({
    InfoType: 1,
    PntInfo: pointInfo,
  })
  //更新时 属性是必选参数
  var attValue = [
    eventNumber.value,
    eventType.value,
    eventLevel.value,
    eventTime.value,
    eventAddress.value,
    carNumber.value,
    driverName.value,
    eventState.value,
  ]
  //创建一个点要素
  var newFeature = new Zondy.Object.Feature({
    fGeom: fGeom,
    GraphicInfo: webGraphicInfo,
    AttValue: attValue,
  })
  //设置要素为点要素
  newFeature.setFType(1)
  newFeature.setFID(fid)
  /*2.创建数据集 */
  //创建一个点要素数据集
  var featureSet = new Zondy.Object.FeatureSet()
  featureSet.clear()
  //设置属性结构
  const cAttStruct = new Zondy.Object.CAttStruct({
    FldName: [
      '事件编号',
      '事件类型',
      '事件等级',
      '发生时间',
      '发生地点',
      '车牌号',
      '驾驶员',
      '处理状态',
    ],
    FldNumber: 8,
    FldType: Array(8).fill('string'),
  })
  featureSet.AttStruct = cAttStruct
  //添加要素到要素数据集
  featureSet.addFeature(newFeature)
  /*3.调用服务 */
  var editService = new Zondy.Service.EditDocFeature(
    Service.docName,
    Service.layerId,
    {
      ip: 'localhost',
      port: '8089', //访问IGServer的端口号，.net版为6163，Java版为8089
    }
  )
  editService.update(featureSet, onPntSuccess)
}
//更新回调
function onPntSuccess(data) {
  if (data.succeed) {
    alert('更新事件成功！')
    ggMap.value?.refresh()
  } else {
    alert('更新事件素失败！')
  }
}
//监听事件提交
watch(
  () => isSubmit.value,
  () => {
    if (isSubmit.value) {
      //更新点的属性值
      //console.log('提交')
      color = eventState.value === '0' ? 6 : eventState.value === '1' ? 4 : 90
      updatePoint()
      isSubmit.value = false
    }
  }
)
onUnmounted(() => {
  try {
    if (map.value) {
      map.value.un('click', handleClick)
      // map.value.removeLayer(layer)
    }
  } catch (error) {
    console.error('清理资源失败:', error)
  }
})
//监听地图实例
watch(
  () => map.value,
  (newMap) => {
    if (newMap) {
      try {
        newMap.on('click', handleClick)
      } catch (error) {
        console.error('初始化地图交互失败:', error)
      }
    }
  },
  { immediate: true }
)
window.addEventListener('click', function (e) {
  top = e.clientY - 340
  left = e.clientX - 150
  console.log(top, left)
  divTop.value = top
  divLeft.value = left
})
</script>

<style lang="scss" scoped>
.update-event {
  position: absolute;
  width: 300px;
  z-index: 99;
  table {
    border: 1px solid #eee;
    td {
      width: 100px;
      height: 20px;
      font-weight: 600;
      font-size: 12px;
      text-align: center;
    }
  }
  .btns {
    width: 200px;
    display: flex;
    gap: 10px;
    margin-top: 5px;
    margin-left: 150px;
    button {
      padding: 2px 8px;
      border-radius: 5px;
      border: 1px solid #ccc;
      cursor: pointer;
    }
    button:first-child {
      background-color: #0f61a1;
      color: white;
    }
  }
}
:deep(.el-card__header) {
  padding: 0;
  p {
    background: skyblue;
    padding: 2px 10px;
    border-radius: 5px;
    font-weight: 400;
    color: white;
  }
  span {
    margin-left: 160px;
    color: white;
    cursor: pointer;
  }
}
:deep(.el-card__body) {
  padding: 10px;
}
.update-event::after {
  content: '';
  position: absolute;
  bottom: -8px;
  left: 50%;
  transform: translateX(-50%);
  width: 0;
  height: 0;
  border-left: 10px solid transparent;
  border-right: 10px solid transparent;
  border-top: 10px solid white;
}
</style>
